/**
 * @author zhouheng
 * @date 2022年03月10日 17:08
 */

package com.atguigu.gulimall.gulimallauth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthContant;
import com.atguigu.common.utils.Constant;
import com.atguigu.common.utils.HttpClient;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.gulimallauth.feign.MemberFeignService;
import com.atguigu.gulimall.gulimallauth.vo.SocialUser;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@Controller
@RequestMapping("/oauth2.0")
public class Auth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @RequestMapping("testAuth2")
    @ResponseBody
    public R testAuth2() {
        return R.ok().setData("success");
    }

    /**
     * 登录成功回调
     * {
     *     "access_token": "2.00b5w4HGbwxc6B0e3d62c666DlN1DD",
     *     "remind_in": "157679999",
     *     "expires_in": 157679999,
     *     "uid": "5605937365",
     *     "isRealName": "true"
     * }
     * 	汀西氟的我是你	---		2.00b5w4HGbwxc6B0e3d62c666DlN1DD
     */
    @GetMapping("/gitee/success") // Oath2Controller
    public String weiBo(@RequestParam("code") String code, HttpSession session, HttpServletResponse servletResponse)
        throws IOException {
        // 根据code换取 Access Token
        Map<String,String> map = new HashMap<>();
        map.put("client_id", "438cdca5c58a9c18272acf0bf3f67184fb796a8ad369f51539348bb4689ee6fa");
        map.put("client_secret", "764d9af9fbba0d60699f4eed7bc40a27455b9ff2c12b9f796e74dbbaeb06d38b");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
        map.put("code", code);
        Map<String, String> headers = new HashMap<>();

        // 去获取token
        HttpResponse response = null;
        try {
            response = HttpUtils.doPost(AuthContant.GITEE_HOST,
                AuthContant.OAUTH_PATH, "post", headers, null, map);
        } catch (Exception e) {
            log.warn("社交登录时远程调用出错 [尝试修复]");
        }

        if (response != null && response.getStatusLine().getStatusCode() == 200){
            // 获取响应体： Access Token
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            // 获取用户信息
            Map<String,String> queryMap = new HashMap<>();
            queryMap.put("access_token", socialUser.getAccessToken());
            HttpResponse userResponse = null;
            try {
                userResponse = HttpUtils
                    .doGet(AuthContant.GITEE_HOST, AuthContant.GITEE_USER_PATH, "get", headers, queryMap);
            } catch (Exception e) {
                log.warn("社交登录时远程调用出错 [尝试修复]");
            }
            if (response.getStatusLine().getStatusCode() == 200){
                // 查询成功
                String userJson = EntityUtils.toString(userResponse.getEntity());
                JSONObject jsonObject = JSON.parseObject(userJson);
                socialUser.setUid(jsonObject.getString("id"));
                socialUser.setNickname(jsonObject.getString("name"));
                socialUser.setUsername(jsonObject.getString("name"));
                socialUser.setGender(1);
                socialUser.setCity("China");
                socialUser.setJob("攻城狮");
                socialUser.setEmail(jsonObject.getString("email"));
            }

            // 相当于我们知道了当前是那个用户
            // 1.如果用户是第一次进来 自动注册进来(为当前社交用户生成一个会员信息 以后这个账户就会关联这个账号)
            R login = memberFeignService.login(socialUser);
            if(login.getCode() == 0){
                MemberRespVo respVo = login.getData("data" ,new TypeReference<MemberRespVo>() {});
                log.info("\n欢迎 [" + respVo.getNickname() + "] 使用社交账号登录");

                // 放入Session回话信息
//                session.setAttribute();
                  session.setAttribute(AuthContant.LOGIN_USER, respVo);
                // 登录成功 跳回首页
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }

        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
